package com.example.myys.data.repository

import com.example.myys.Constants
import com.example.myys.MyApplication
import com.example.myys.data.InventoryDatabase
import com.example.myys.data.entity.ChapterBean
import com.example.myys.data.entity.DataBean
import com.example.myys.network.HtmlClient

class ComicRepository {
    val htmlClient = HtmlClient
    val comicDao = InventoryDatabase.getInstance(MyApplication.instance).dataBeanDao()
    val chapterDao = InventoryDatabase.getInstance(MyApplication.instance).chapterDao()
    val TYPE = Constants.MH
    val SOURCE_NAME = "Mh"

    //获取漫画推荐
    suspend fun getComicRecommend(): List<DataBean>? {
        val htmllist = htmlClient.getRecommend(SOURCE_NAME, "")
        var sctj = htmllist
        return sctj
    }

    //搜索漫画
    suspend fun getComicByKeyword(keyword: String): List<DataBean>? {
        return htmlClient.getSearchByKeword(SOURCE_NAME, keyword)
    }

    //加入书架
    suspend fun addComicShelf(dataBean: DataBean) {
        dataBean.type = TYPE
        val id = comicDao.insert(dataBean)
        val chapterList = htmlClient.getChapterList(SOURCE_NAME, dataBean.url, id.toInt())
        if (chapterList != null) {
            chapterDao.insertList(chapterList)
        }
    }

    //获取书架
    suspend fun getComicShelf(): List<DataBean> {
        return comicDao.getListByType(TYPE)
    }

    //删除收藏
    suspend fun deleteShelf(dataBean: DataBean) {
        val chapters = chapterDao.getListByDataBeanId(dataBean.id)
        chapterDao.deleteList(chapters)
        comicDao.delete(dataBean)
    }

    //获取列表
    suspend fun getComicChapterList(dataUrl: String, dataId: Int): List<ChapterBean> {
        var chapterList = chapterDao.getListByDataBeanId(dataId)
        if (chapterList.isEmpty()) {
            chapterList = htmlClient.getChapterList(SOURCE_NAME, dataUrl, dataId)!!
        }
        return chapterList
    }

    //获取内容
    suspend fun getComicContent(chapterUrl: String, id: Int, dataId: Int): String? {
        var chapter = chapterDao.getChapterContent(id, dataId)
        var content = ""
        if (chapter != null && chapter.content.isNotEmpty()) {
            content = chapter.content
        } else {
            val htmlcontent = htmlClient.getChapterContent(SOURCE_NAME, chapterUrl)
            if (htmlcontent != null) {
                content = htmlcontent
                if (chapter != null) {
                    chapter.content = htmlcontent
                    chapterDao.update(chapter)
                }
            }
        }
        return content
    }
}